package controller

import (
	"errors"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"tino_manager/dao"
	"tino_manager/dto"
	"tino_manager/middleware"
)

type DataController struct {
}

func DataRegister(group *gin.RouterGroup) {
	data := &DataController{}
	//查询场地的预约和浏览量
	group.POST("/site_data", data.SiteData)
	//管理员查询登录过几次
	group.POST("/login_info", middleware.WeAppMiddleware(), data.LoginInfo)
}
func (d *DataController) SiteData(c *gin.Context) {
	params := &dto.DataSiteInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败,请稍后重试"), true)
		return
	}
	browserTotal := int64(0)
	tx.Model(&dao.Browse{}).Where("site_id = ? AND is_delete = 0", params.SiteId).Count(&browserTotal)
	reservationTotal := int64(0)
	tx.Model(&dao.Reservation{}).Where("site_id = ? AND is_delete = 0", params.SiteId).Count(&reservationTotal)
	middleware.ResponseSuccess(c, map[string]interface{}{
		"browser_total":     browserTotal,
		"reservation_total": reservationTotal,
	}, true)
}
func (d *DataController) LoginInfo(c *gin.Context) {
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	login := &dao.Log{}
	total := int64(0)
	if result := tx.Model(&dao.Log{}).Where("created_by = ?", value).Count(&total).Last(login); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	middleware.ResponseSuccess(c, map[string]interface{}{
		"total": total,
		"time":  login.CreatedAt.Format("2006-01-02 15:04:05"),
	}, true)
}
